import pymongo
from conn import mongo_client as client
import random

from ex import get_beijing_time


def is_transaction_supported(client):
    # 获取 MongoDB 服务器信息
    server_info = client.server_info()
    # 提取版本号
    version = server_info.get("version")
    major, minor, _ = map(int, version.split(".")[:3])
    # 检查版本是否大于等于 4.0
    if major < 4:
        return False
    # 尝试在一个事务中插入一条数据
    with client.start_session() as session, session.start_transaction():
        collection = client.test.aa
        collection.insert_one({"cur": get_beijing_time()}, session=session)

    row = collection.find({}).sort({"_id": -1}).limit(1)[0]
    print(row["cur"], row["cur"].tzinfo)


if __name__ == "__main__":
    # 调用函数判断是否支持事务
    result = is_transaction_supported(client)
    if result:
        print("MongoDB 支持事务。")
    else:
        print("MongoDB 不支持事务。")
